import 'package:flutter/material.dart';

import 'state_config.dart';
import 'state_ctrl.dart';
import 'state_model.dart';

/// 缺省页
class StateWidget extends StatelessWidget {
  /// 控制器
  final StateCtrl ctrl;

  //内容
  final Widget child;

  final Widget Function(StateModel)? buildLoading;
  final Widget Function(StateModel)? buildEmpty;
  final Widget Function(StateModel, VoidCallback? onTapRetry)? buildError;

  const StateWidget({
    super.key,
    required this.child,
    required this.ctrl,
    this.buildLoading,
    this.buildEmpty,
    this.buildError,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        child,
        ValueListenableBuilder(
          valueListenable: ctrl,
          builder: (context, state, child) {
            return _buildStateView(state);
          },
        ),
      ],
    );
  }

  Widget _buildStateView(StateModel state) {
    Widget? widget;

    switch (state.state) {
      case StateEnum.loading:
        {
          widget = buildLoading?.call(state) ?? StateConfig.buildLoading?.call(state);
        }
      case StateEnum.content:
        return const SizedBox.shrink();
      case StateEnum.empty:
        {
          widget = buildEmpty?.call(state) ?? StateConfig.buildEmpty?.call(state);
        }
      case StateEnum.error:
        {
          widget = buildError?.call(state, ctrl.showLoading) ?? StateConfig.buildError?.call(state, ctrl.showLoading);
        }
    }
    return widget ?? const SizedBox.shrink();
  }
}
